<?php

namespace App\Admin\Controllers;

use App\Admin\Repositories\User;
use App\Models\EacooProv;
use App\Models\ReservationServiceCategory;
use App\Models\SystemRegion;
use App\Models\UserAddress;
use Dcat\Admin\Form;
use Dcat\Admin\Grid;
use Dcat\Admin\Show;
use Dcat\Admin\Controllers\AdminController;
use Illuminate\Http\Request;
use App\Models\User as prevUser;
use Illuminate\Support\Facades\Hash;
use App\Models\User as UserModel;

class UserController extends AdminController
{
    /**
     * Make a grid builder.
     *
     * @return Grid
     */
    protected function grid()
    {
        return Grid::make(new User(), function (Grid $grid) {
            $grid->column('id')->sortable();
            $grid->column('user_name');

            $grid->column('phone_num');

            $grid->column('address_region');


            $grid->column('fans_num');
            $grid->column('follow_num');
            $grid->column('article_num');
            $grid->column('integral_num') -> sortable();
            $grid->column('coins_num');
            $grid->column('sex') ->display(function($sex){
                return $sex == 1 ? '男' : '女';
            });
            $grid->column('role') ->display(function($role){
                $service_catid = $this -> service_catid;
                $service_name = ReservationServiceCategory::where('id',$service_catid) -> value('name');
                return $role ? ($role == 2 ? '专家（'.$service_name.'）' : '乡村振兴员') : '普通用户';

            });

            $grid->column('created_at', '注册时间');
            $grid->selector(function (Grid\Tools\Selector $selector) {
                $category = ReservationServiceCategory::pluck('name','id');

                $system_regions = SystemRegion::pluck('region_name','region_code');
                $system_regions[]  = '其他';
                $selector->selectOne('service_catid', '服务类型', $category);
                $selector->selectOne('role', '角色', [0 => '普通用户', 1 => '乡村振兴员',2 => '专家']);
                $selector->selectOne('region_code', '地区', $system_regions);
            });

            $grid->quickSearch(['user_name', 'phone_num', 'id_num'])->placeholder('搜索...');
            // 在行操作 action 中使用
            $grid->actions(function ($actions) {
                // 获取当前行主键值
                $id = $actions->getKey();
                $editPage = admin_base_path('users/integral_records?user_id='.$id);

                $actions->append("<a href=".$editPage."><i class='fa fa-eye'>积分管理</i></a>");
            });

        });
    }

    /**
     * Make a show builder.
     *
     * @param mixed $id
     *
     * @return Show
     */
    protected function detail($id)
    {
        return Show::make($id, new User(), function (Show $show) {
            $show->field('id');
            $show->field('user_name');
            $show->field('real_name');

            $show->field('phone_num');
            $show->field('id_num');
            $show->field('address_region');
            $show->field('address_detailed');
            $show->field('head_portrait') ->image();
            $show->field('person_profile');
            $show->field('fans_num');
            $show->field('follow_num');
            $show->field('article_num');
            $show->field('integral_num');
            $show->field('coins_num');
            $show->field('sex') ->as(function($sex){
                return $sex == 1 ? '男' : '女';
            });
            $show->field('role') ->as(function($role){
                return $role ? ($role == 2 ? '专家' : '乡村振兴员' ) : '普通用户';
            });
            $show->field('service_catid') ->as(function($service_catid){
                $service_name = ReservationServiceCategory::where('id',$service_catid) -> value('name');
                return $service_name ?: '';
            });
            $show->field('inviter_user_id') ->as(function($inviter_user_id){
                $user = prevUser::find($inviter_user_id);
                return $user ? ($user -> real_name ?: $user -> user_name ) : '';
            });
            $show->field('wx_id');
            $show->field('qq_id');
            $show->field('wb_id');
            $show->field('last_login_time');
            $show->field('created_at');
            $show->field('updated_at');
        });
    }




    /**
     * Make a form builder.
     *
     * @return Form
     */
    protected function form()
    {
        return Form::make(UserModel::with(['user_address']), function (Form $form) {
            $form->display('id');
            $form->text('user_name') ->required();
            $form->text('real_name');
            $form->text('user_pwd');
            $form->text('phone_num') ->required();
            $form->text('id_num');

            $province = EacooProv::pluck('prov as text','code as id');
            $form->select('user_address.prov','省份')
                ->options($province)
                ->loads('user_address.city','/api/address');

            $form->select('user_address.city','城市') ->loads('user_address.country','/api/address');
            $form->select('user_address.country','乡/县') -> loads('user_address.town', '/api/address');
            $form->select('user_address.town','镇');

            $form->text('address_detailed');
            $form->image('head_portrait')->move('user/'.date('Y-m-d'))->autoUpload();
            $form->text('person_profile');
            $form->radio('sex')->options(['1' => '男','2' => '女']) ->default(1);

            $form->radio('role')->when(2, function (Form $form) {
                $service_category = ReservationServiceCategory::pluck('name','id');
                $form->select('service_catid','农业服务类型')->options($service_category);
            }) ->options(['0' => '会员','1' => '乡村振兴员','2' => '专家']) ->default('0');

//            $form->text('region_code');
//            $form->text('inviter_user_id');
            $form->text('wx_id');
            $form->text('qq_id');
            $form->text('wb_id');
            $form->hidden('address_region');

            $form->display('created_at');
            $form->display('updated_at');

            $form->submitted(function ($form) {
                $form->user_pwd = Hash::make($form ->user_pwd);
                $form->service_catid = $form ->service_catid ?: 0;
                $prov = User::getNameByCode($form->user_address['prov'] ?? null);
                $city = User::getNameByCode($form->user_address['city'] ?? null);
                $country = User::getNameByCode($form->user_address['country'] ?? null);
                $town = User::getNameByCode($form->user_address['town'] ?? null);
                if($prov){
                    $form->address_region = $prov . $city . $country . $town;
                }else{
                    $form->address_region = '';
                }
                $form->region_code = $form->user_address['town'] ?? null;

            });
            $form ->saving(function($form){
//                $form->deleteInput(['province','city','country','town','village']);
            });

            $form->saved(function (Form $form,$result) {
                if ($form->user_address['town'] ?? null) {
                    UserModel::where('id', $form -> getKey()) ->update(['region_code' => $form->user_address['town']]);
                }

            });

        });
    }
}
